package com.wrial.kind.concurrency;
/*
 * @Author  Wrial
 * @Date Created in 14:35 2020/8/10
 * @Description
 */

/**
 * 交替打印1和2 打印10次
 */
public class Print1And2 {

    private static final Object lock = new Object();
    private static int state = 1;

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    while (state!=1){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(1);
                    state = 2;
                    lock.notifyAll();
                }
            }

        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                   while (state!=2){
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                    System.out.println(2);
                    state = 1;
                    lock.notifyAll();
                }
            }

        }).start();


    }
}
